/*
 * Created on Sep 7, 2008
 */
package com.mgmaps.platform;

import java.util.TimerTask;
import javax.microedition.media.Control;
import com.mgmaps.app.APPSettings;
import com.mgmaps.utils.ExtLogger;
import net.rim.blackberry.api.browser.Browser;
import net.rim.blackberry.api.phone.Phone;
import net.rim.device.api.media.control.AudioPathControl;
import net.rim.device.api.system.*;
import net.rim.device.api.servicebook.ServiceBook;
import net.rim.device.api.servicebook.ServiceRecord;

public class PlatformBB implements IPlatformHandler {
  
  boolean backlightIsOn;
  private boolean backlightScheduled;
  
  private static final String[] HTTP_APPEND_WAP = {
    ";WapGatewayAPN=proxy;WapGatewayIP=10.250.250.250",
    ";WapGatewayAPN=wap.voicestream.com;WapGatewayIP=216.155.165.50",
    ";WapGatewayAPN=blackberry.net;WapGatewayIP=66.209.11.61;WapGatewayPort=9203",
    ";WapGatewayAPN=blackberry.net;WapGatewayIP=208.200.67.150", // duplicate?
    ";WapGatewayAPN=;WapGatewayIP=216.198.139.70;WapGatewayPort=9203",
    ";WapGatewayAPN=wap.o2.co.uk;WapGatewayIP=193.113.200.195",
    ";WapGatewayAPN=wap.viaginterkorn.de;WapGatewayIP=195.182.114.52", 
    ";WapGatewayAPN=wap.t-dl.de;WapGatewayIP=193.254.160.2",
    ";WapGatewayAPN=wap.movistar.es;WapGatewayIP=192.168.80.21",
    ";WapGatewayAPN=telstra.internet;WapGatewayIP=10.1.1.150",
    ";WapGatewayAPN=wap.tim.it;WapGatewayIP=213.26.205.1",
    ";WapGatewayAPN=airtelwap.es;WapGatewayIP=212.73.32.10;TunnelAuthPassword=wap125;TunnelAuthUsername=wap@wap",
    ";WapGatewayAPN=wap.vodafone.co.uk;WapGatewayIP=212.183.137.12",
    ";WapGatewayAPN=wapsfr;WapGatewayIP=195.115.25.129",
    ";WapGatewayAPN=mworld.be;WapGatewayIP=212.65.63.143",
    ";WapGatewayAPN=orangewap;WapGatewayIP=192.168.71.35",
    ";WapGatewayAPN=general.t-mobile.uk;WapGatewayIP=149.254.1.10", 
    ";WapGatewayAPN=wap.vodafone.de;WapGatewayIP=139.7.29.1",
    ";WapGatewayAPN=A1.net;WapGatewayIP=194.48.124.71",
    ";WapGatewayAPN=wap.proximus.be;WapGatewayIP=10.253.7.3",
    ";WapGatewayAPN=internet.simobil.si;WapGatewayIP=80.95.224.17",
    ";WapGatewayAPN=gprs.swisscom.ch;WapGatewayIP=192.168.210.1",
    ";WapGatewayAPN=gprs0.vipnet.hr;WapGatewayIP=212.91.99.91",
    ";WapGatewayAPN=live.vodafone.com;WapGatewayIP=10.202.2.60",
    ";WapGatewayAPN=wap.vodafone.com.eg;WapGatewayIP=163.121.178.2",
    ";WapGatewayAPN=wap.vodafone.gr;WapGatewayIP=213.249.19.49",
    ";WapGatewayAPN=wap.vodafone.net;WapGatewayIP=10.9.8.7", 
    ";WapGatewayAPN=live.vodafone.com;WapGatewayIP=10.24.59.100", // NOT duplicate -- used with distribution channels
    ";WapGatewayAPN=wap.omnitel.it;WapGatewayIP=10.128.201.76",
    ";WapGatewayAPN=wap.vodafone.com.mt;WapGatewayIP=10.12.0.2",
    ";WapGatewayAPN=blackberry.vodafone.nl;WapGatewayIP=192.168.251.150;TunnelAuthPassword=vodafone;TunnelAuthUsername=vodafone",
    ";WapGatewayAPN=www.vodafone.net.nz;WapGatewayIP=172.30.38.3",
    ";WapGatewayAPN=wap.vodafone.pt;WapGatewayIP=172.16.19.50",
    ";WapGatewayAPN=internet.vodafone.net;WapGatewayIP=172.30.253.241",
    ";WapGatewayAPN=vlive;WapGatewayIP=196.6.128.12",
    ";WapGatewayAPN=vf.pt.lu;WapGatewayIP=194.154.192.98",
    ";WapGatewayAPN=internet;WapGatewayIP=10.11.10.11", 
    ";WapGatewayAPN=live.vodafone.com;WapGatewayIP=193.230.161.231",
    ";WapGatewayAPN=live.gprs.is;WapGatewayIP=10.22.0.22",
    ";WapGatewayAPN=wap-gprs.mtel.bg;WapGatewayIP=213.226.6.65",
    ";WapGatewayAPN=vflive;WapGatewayIP=216.65.136.226",
    ";WapGatewayAPN=wap.gocbw.com;WapGatewayIP=216.68.79.199;TunnelAuthUsername=cbw",
    ";WapGatewayAPN=wap.sunrise.ch;WapGatewayIP=212.35.34.70",
    ";WapGatewayAPN=internet.com;WapGatewayIP=207.236.197.199;WapGatewayPort=9203",
    ";WapGatewayAPN=wap.dol.ie;WapGatewayIP=192.168.90.74;TunnelAuthPassword=gprs;TunnelAuthUsername=gprs",
  };
  
  class BacklightTimerTask extends TimerTask {
    public void run() {
      if (backlightIsOn)
        Backlight.enable(true, 255);
    }
  }

  /**
   * Start the vibration.
   * @param length length in milliseconds
   * @see com.mgmaps.platform.trapster.platform.IPlatformHandler#vibrate(int)
   */
  public void vibrate(final int length) {
    Alert.startVibrate(length);
  }

  /**
   * Set audio path
   * @param controls controls available for the player
   * @param device device to route audio to
   * @return true if successful
   * @see com.mgmaps.platform.trapster.platform.IPlatformHandler#setAudioPath(javax.microedition.media.Control[], int)
   */
  public boolean setAudioPath(Control[] controls, int device) {
    boolean found = false;
    for (int i = 0; i < controls.length; i++)
      if (controls[i] instanceof AudioPathControl) {
        AudioPathControl apc = (AudioPathControl) controls[i];
        try {
          apc.setAudioPath(device);
        }
        catch (Exception e) {
          ExtLogger.handle(e, false, "Error setting audio path");
          return false;
        }
        found = true;
      }
    return found;
  }

  /**
   * Set volume using device-dependent code.
   * @param vol new volume
   * @see com.mgmaps.platform.trapster.platform.IPlatformHandler#setVolume(int)
   */
  public void setVolume(int vol) {
    // Alert.setVolume(vol);
  }
  
  public String getDeviceID() {
    String devID = Integer.toString(DeviceInfo.getDeviceId(), 16);
    if (devID == null)
      return "";
    return devID.trim();
  }
  
  /**
   * Get device name.
   * @return device name for blackberry.
   */
  public String getDeviceName() {
    String devInfo = DeviceInfo.getDeviceName();
    if (devInfo == null)
      return "";
    return devInfo.trim();
  }
  
  /**
   * Get user agent.
   * 
   * @return user agent string
   * @see com.mgmaps.platform.trapster.platform.IPlatformHandler#getUserAgent()
   */
  public String getUserAgent() {
    String osVersion = DeviceInfo.getPlatformVersion();
    String devName = DeviceInfo.getDeviceName();
    if (osVersion == null)
      osVersion = "?";
    if (devName == null)
      devName = "?";
    return "Blackberry" + devName + "/" + osVersion;
  }
  
  /**
   * Get carrier name.
   * @return name of network
   * @see com.mgmaps.platform.trapster.platform.IPlatformHandler#getCarrierName()
   */
  public String getCarrierName() {
    String carrier = RadioInfo.getCurrentNetworkName();
    if (carrier == null)
      return "";
    return carrier.trim();
  }
  
  /**
   * Get phone number.
   * @return phone number
   * @see com.mgmaps.platform.trapster.platform.IPlatformHandler#getPhoneNumber()
   */
  public String getPhoneNumber() {
    String phoneNumber = Phone.getDevicePhoneNumber(false);
    if (phoneNumber == null || phoneNumber.equalsIgnoreCase("unknown"))
      return "";
    return phoneNumber.trim();
  }

  /**
   * Set backlight always on.
   */
  public void backlightOn() {
    backlightIsOn = true;
    if (!backlightScheduled) {
      APPSettings.timer.schedule(new BacklightTimerTask(), 5000, 5000);
      backlightScheduled = true;
    }
  }

  /**
   * Turn backlight off / disable at exit.
   */
  public void backlightOff() {
    backlightIsOn = false;
    Backlight.enable(true, Backlight.getTimeoutDefault());
  }

	/*
	public String defaultConnectionString() {
		ServiceBook sb = ServiceBook.getSB();
		ServiceRecord[] records = sb.findRecordsByCid("IPPP");
		if (records != null) {
			for (int i = records.length - 1; i >= 0; i--) {
				ServiceRecord rec = records[i];
				if (rec.isValid() && !rec.isDisabled()) {
					if (rec.getEncryptionMode() == ServiceRecord.ENCRYPT_RIM) {
						// MDS - disabled for now.
						return Settings.httpExtensions[1];
					} else {
						// BIS
						return Settings.httpExtensions[2];
					}
				}
			}
		}
		return Settings.httpExtensions[3];// No IPPP records, fallback to TCP. User
									// will need to enter the APN settings in
									// the Options app.
	}
	*/

  /**
   * Get extension string.
   * @return HTTP extension string, "" for non-blackberry
   * @see com.mgmaps.platform.IPlatformHandler#getBlackberryHTTPExtension()
   */
  public String getBlackberryHTTPExtension() {
    // wifi
    /* final String osver = getOSVersion();
    if (osver.compareTo("4.3") < 0) { */
      if ((RadioInfo.getActiveWAFs() & RadioInfo.WAF_WLAN) != 0 && RadioInfo.getSignalLevel(RadioInfo.WAF_WLAN) != RadioInfo.LEVEL_NO_COVERAGE)
        return APPSettings.httpExtensions[4];
    /* }
    else {
      if (WLANInfo.getWLANState() == WLANInfo.WLAN_STATE_CONNECTED)
        return Settings.httpExtensions[4];
    } */
    
    try {
      final ServiceBook sb = ServiceBook.getSB();
      
      // IPPP
      final ServiceRecord[] recs = sb.findRecordsByCid("IPPP");
      if (recs != null && recs.length != 0) {
        boolean encmode = false;
        final int len = recs.length;
        for (int i=0; i<len; i++) {
          final ServiceRecord sr = recs[i];
          if (!sr.isValid() || sr.isDisabled())
            continue;
          final String name = sr.getName();
          if (sr.getEncryptionMode() == 2) {
            encmode = true;
            continue;
          }
          if (name != null && (name.startsWith("IPPP for BIBS") || name.startsWith("IPPP for BIS-B") || name.startsWith("Internet ICS")))
            return APPSettings.httpExtensions[2];
        }
        if (encmode)
          return APPSettings.httpExtensions[1];
        else
          return APPSettings.httpExtensions[3];
      }
      
      // detect WAP access points
      else {
        final ServiceRecord[] recs2 = sb.findRecordsByCid(Browser.CID_BROWSERCONFIG);
        if (recs2 != null && recs2.length != 0) {
          final int len = recs2.length;
          for (int i=0; i<len; i++) {
            final ServiceRecord sr = recs2[i];
            if (!sr.isValid() || sr.isDisabled())
              continue;
            final String transportUID = Browser.getTransportUid(sr);
            final ServiceRecord[] recs3 = sb.findRecordsByUid(transportUID);
            final int len2 = recs3.length;
            for (int l=0; l<len2; i++) {
              final String s1 = ";WapGatewayAPN=" + recs3[l].getAPN() + ";";
              for (int k=0; k<HTTP_APPEND_WAP.length; k++)
                if (HTTP_APPEND_WAP[k].startsWith(s1))
                  return HTTP_APPEND_WAP[k];
            }
          }
        }
        // else
        //   return Settings.httpExtensions[0];
      }
    }
    catch (Exception ex) {
      ExtLogger.handle(ex, false, "Error auto-detecting Blackberry extension string");
    }
    
    return APPSettings.httpExtensions[3];
  }

  /**
   * Open a website in the default browser.
   * @param url URL to open
   */
  public void openWebsite(String url) {
    Browser.getDefaultSession().displayPage(url);
  }
}
